import React, {useEffect, useImperativeHandle} from 'react';
import {Field, Form, Input, List, Select, Select} from '@alifd/next';

const FormItem = Form.Item;

export type ActionType = 'add' | 'edit' | 'preview';

const formItemLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 20}
};

export interface OperaitionProps {
  /**
   * 操作类型, 以此来标识是添加、编辑、还是查看
   */
  actionType: ActionType;

  /**
   * 数据源
   */
  dataSource: any;
}

export interface OperationRef {
  getValues(callback: (vals: object) => void): void;
}

const Operation: React.ForwardRefRenderFunction<OperationRef, OperaitionProps> = (props, ref) => {
  const Option = Select.Option;
  const {
    actionType, onOk = () => {
    }
  } = props;
  onOk();
  const dataSource = props.dataSource || {};
  const field = Field.useField([]);
  useEffect(() => {
    field.reset();
    if (dataSource) {
      // console.log(dataSource);
      const newValues = {
        ...dataSource
      };
      field.setValues(newValues);
    }
  }, [field, dataSource]);
  useImperativeHandle<OperationRef, OperationRef>(
    ref,
    () => {
      return {
        getValues(callback: (vals: object) => void) {
          field.validate((errors, values): void => {
            if (errors) {
              return;
            }
            callback(values);
          })
        }
      };
    }
  );

  const isPreview = actionType === 'preview';

  return (
    <>
      <Form
        isPreview={isPreview}
        fullWidth
        labelAlign={isPreview ? 'left' : 'top'}
        field={field}
        {...formItemLayout}
      >
        <FormItem
          label="id:"
          required={!isPreview}
          requiredMessage="必填"
        >
          <Input
            disabled
            {...field.init('id')}
          />
        </FormItem>

        <FormItem
          label="商品名称:"
          required={!isPreview}
          requiredMessage="必填"
        >
          <Input
            name="name"
          />
        </FormItem>

        <FormItem
          label="兑换价格:"
          required={!isPreview}
          requiredMessage="必填"
        >
          <Input
            name="price"
          />
        </FormItem>

        <FormItem
          label="钱包类型:"
          required={!isPreview}
          requiredMessage="type"
        >
          <Select name="type">
            <Option value="0">普通钱包</Option>
            <Option value="1">打工钱包</Option>
          </Select>
        </FormItem>
      </Form>
    </>
  );
}

export default React.forwardRef(Operation);
